package service

import (
	"duoke/context"
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/gmd5"
	"duoke/utils/orm"
	"errors"
	"github.com/gin-gonic/gin"
)

var Goods = new(goodsService)

type goodsService struct{}

func (s *goodsService) GetById(id int, field string) (*model.ReqGoods, error) {
	data := new(model.ReqGoods)
	has, err := orm.Db.ID(id).Cols(field).Get(data)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("该商品不存在")
	}
	return data, nil
}

func (s *goodsService) List(c *gin.Context, req model.ReqList) ([]model.ReqGoods, error) {
	accountR, _ := Request.Account(c)
	list := make([]model.ReqGoods, 0)
	query := orm.Db.Desc("id")
	//判断子账户
	if accountR.Role == "goods" {
		query = query.Where("id IN(" + accountR.GoodsIds + ")")
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	if req.Keyword != "" {
		query = query.Where("title like ?", "%"+req.Keyword+"%")
	}
	if req.State != "" {
		query = query.Where("state =?", req.State)
	}
	err := query.Find(&list)
	if err != nil {
		return nil, err
	}
	for index, item := range list {
		list[index].ShareQrcodeUrl = context.Global.Domain + "/mp/qrcode/?acid=" + gconv.String(accountR.Id) + "&type=share&goodsId=" + gconv.String(item.Id) + "&is_hyaline=0"
		list[index].Income = s.Income(item.Id)
		list[index].Sales = s.Sales(item.Id)
		list[index].Token = gmd5.MustEncrypt(gconv.String(item.Id) + item.ScreenboardPassword)
	}
	return list, nil
}
func (s *goodsService) ListWhere(c *gin.Context, req model.ReqList, where string) ([]model.ReqGoods, error) {
	accountR, _ := Request.Account(c)
	list := make([]model.ReqGoods, 0)
	query := orm.Db.Desc("id")
	//判断子账户
	if accountR.Role == "goods" {
		query = query.Where("id IN(?)", accountR.GoodsIds)
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	if req.Keyword != "" {
		query = query.Where("title =?", req.Keyword)
	}
	if req.State != "" {
		query = query.Where("state =?", req.State)
	}
	err := query.Where(where).MustLogSQL().Find(&list)
	if err != nil {
		return nil, err
	}
	for index, item := range list {
		list[index].ShareQrcodeUrl = context.Global.Domain + "/mp/qrcode/?acid=" + gconv.String(accountR.Id) + "&type=share&goodsId=" + gconv.String(item.Id)
		list[index].Income = s.Income(item.Id)
		list[index].Sales = s.Sales(item.Id)
		list[index].Token = gmd5.MustEncrypt(gconv.String(item.Id) + item.ScreenboardPassword)
	}
	return list, nil
}
func (s *goodsService) Save(c *gin.Context, req model.ReqGoods) error {
	accountR, _ := Request.Account(c)
	if req.Id > 0 {
		_, err := s.GetById(req.Id, "")
		if err != nil {
			return err
		}
		// 保存数据
		_, err = orm.Db.ID(req.Id).Omit("acid,share_timeline,share_app_message,views").AllCols().Update(req)
		if err != nil {
			return err
		}
	} else {
		req.Acid = accountR.Id
		req.State = 1
		if accountR.Role == "goods" {
			req.Acid = accountR.Pid
		}
		// 保存数据
		_, err := orm.Db.Insert(req)
		if err != nil {
			return err
		}
		// 绑定商品ID
		newAccount := new(tables.Account)
		has, err := orm.Db.ID(accountR.Id).Get(newAccount)
		if has {
			newGoods := new(tables.Goods)
			_, _ = orm.Db.Desc("id").Where("acid= ? AND title=?", req.Acid, req.Title).Get(newGoods)
			if newAccount.BindGoodsIds != "" {
				newAccount.BindGoodsIds = newAccount.BindGoodsIds + "," + gconv.String(newGoods.Id)
			} else {
				newAccount.BindGoodsIds = gconv.String(newGoods.Id)
			}
			_, err = orm.Db.ID(accountR.Id).Cols("bind_goods_ids").Update(newAccount)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func (s *goodsService) Del(req model.ReqIds) error {
	_, err := orm.Db.In("id", req.Ids).Delete(new(tables.Goods))
	if err != nil {
		return err
	}
	return nil
}

func (s *goodsService) Copy(c *gin.Context, req model.ReqId) error {
	accountR, _ := Request.Account(c)
	goods, err := s.GetById(req.Id, "")
	//if accountR.Role == "goods" {
	//	return errors.New("该账户没有创建新商品权限")
	//}
	// 保存数据
	goods.Id = 0
	_, err = orm.Db.Insert(goods)
	if err != nil {
		return err
	}
	// 绑定商品ID
	newAccount := new(tables.Account)
	has, err := orm.Db.ID(accountR.Id).Get(newAccount)
	if has {
		if newAccount.BindGoodsIds != "" {
			newAccount.BindGoodsIds = newAccount.BindGoodsIds + "," + gconv.String(goods.Id)
		} else {
			newAccount.BindGoodsIds = gconv.String(goods.Id)
		}
		_, err = orm.Db.ID(accountR.Id).Cols("bind_goods_ids").Update(newAccount)
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *goodsService) State(req model.ReqId) error {
	goods, err := s.GetById(req.Id, "")
	if err != nil {
		return err
	}
	if goods.State == 1 {
		goods.State = 0
		_, err = orm.Db.ID(goods.Id).Cols("state").Update(goods)
		if err != nil {
			return err
		}
	} else {
		goods.State = 1
		_, err = orm.Db.ID(goods.Id).Cols("state").Update(goods)
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *goodsService) Views(goods model.ReqGoods) error {
	goods.Views = goods.Views + 1
	_, err := orm.Db.ID(goods.Id).Update(goods)
	if err != nil {
		return err
	}
	return nil
}

// 商品总收入
func (s *goodsService) Income(goodsId int) float32 {
	order := new(tables.Order)
	total, _ := orm.Db.
		Where("goods_id =?", goodsId).
		Where("pay_state =?", 1).
		Where("refund_state =?", 0).
		Where("is_robot =?", 0).
		Sum(order, "pay_amount")
	return float32(total)
}

// 商品总销量
func (s *goodsService) Sales(goodsId int) int64 {
	order := new(tables.Order)
	total, _ := orm.Db.
		Where("goods_id =?", goodsId).
		Where("pay_state =?", 1).
		Where("refund_state =?", 0).
		Where("is_robot =?", 0).
		Count(order)
	return total
}
